
#include <string>
using std::string;

#include "as_socket.hxx"
#include "minilog_static.hxx"

#define HOST_ADDR_DEFAULT        "0.0.0.0:8888"
static string ipAddress = HOST_ADDR_DEFAULT;

#if 0
#include <regex>
using std::regex;
using std::smatch;
bool checkAddress(const string &ipstr)
{
    //regex pattern("((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
    regex pattern("(?:((?:d|[1-9]d|1d{2}|2[0-5][0-5]).(?:d|[1-9]d|1d{2}|2[0-5][0-5]).(?:d|[1-9]d|1d{2}|2[0-5][0-5]).(?:d|[1-9]d|1d{2}|2[0-5][0-5]))d+:(6[0-5]{2}[0-3][0-5]|[1-5]d{4}|[1-9]d{1,3}|[0-9]))");
    smatch res;
    if(regex_match(ipstr,res,pattern)){
        return true;
    }
    return false;
}
#else
bool checkAddress(const string &ipstr)
{
    const char* hostName = ipstr.c_str();
    long int port;
    char hostNameChar[256];
    if (sscanf(hostName, "%[^:]:%ld", hostNameChar, &port) != 2)
    {
        // It did not work.
        // scanf() returns the number of matched tokens.
        fprintf(stdout, "Fail\n");
        return false;

        exit(1);
    }
    if( port < 0 || port > 65535)
    {
        return false;
    }
    //fprintf(stdout, "Host(%s) Port(%ld)\n", hostNameChar, port);
    LogD("ip :", hostNameChar, ", port:", port, "]");
    return true;
}
#endif

// 初步检查地址的有效性
void socketTrySetaddress(const string & addr)
{
    if(!checkAddress(addr))
    {
        LogW("Invalid addr: [", addr, "]");
        LogW("try use [", HOST_ADDR_DEFAULT, "] again?");
        exit(EXIT_FAILURE);
    }

    LogI("Try use address : ", addr);
    ipAddress = addr;
}

string & socketGetaddress(void)
{
    return ipAddress;
}
